/**
 * 路由配置
 * 职责：路由定义、权限控制、导航守卫
 */
import { createRouter, createWebHistory } from "vue-router"
import { useUsersStore } from "@/stores/modules/user"

// 布局组件
export const Layout = () => import("@/layout/index.vue");

// 公共路由
export const constantRoutes = [
  {
    path: "/login",
    component: () => import("@/views/auth/Login.vue"),
    meta: {
      title: "登录",
      noLayout: true,
    },
  },
  {
    path: "/",
    redirect: "/dashboard",
  },
  {
    path: "/dashboard",
    component: Layout,
    children: [
      {
        path: "",
        name: "Dashboard",
        component: () => import("@/views/dashboard/index.vue"),
        meta: { title: "首页" },
      },
    ],
  },
  {
    path: "/profile",
    component: Layout,
    children: [
      {
        path: "",
        name: "Profile",
        component: () => import("@/views/profile/index.vue"),
        meta: { title: "个人中心" },
      },
    ],
  },
  {
    path: "/chat",
    component: Layout,
    children: [
      {
        path: "",
        name: "Chat",
        component: () => import("@/views/chat/index.vue"),
        meta: { title: "聊天室" },
      },
    ],
  },
  {
    path: "/problemSet",
    component: Layout,
    children: [
      {
        path: "",
        name: "ProblemSetList",
        component: () => import("@/views/problemSet/index.vue"),
        meta: { title: "题单广场" },
      },
      {
        path: ":id",
        name: "ProblemSetDetail",
        component: () => import("@/views/problemSet/detail.vue"),
        meta: { title: "题单详情", hidden: true },
      },
    ],
  },
];

// 权限路由（管理员功能）
export const asyncRoutes = [
  {
    path: "/admin",
    component: Layout,
    meta: {
      title: "系统管理",
      roles: ["ADMIN"],
    },
    children: [
      {
        path: "user",
        name: "AdminUser",
        component: () => import("@/views/admin/user/index.vue"),
        meta: { title: "用户管理" },
      },
      {
        path: "problem",
        name: "AdminProblem",
        component: () => import("@/views/admin/problem/index.vue"),
        meta: { title: "题目管理" },
      },
      {
        path: "problemSet",
        name: "AdminProblemSet",
        component: () => import("@/views/admin/problemSet/index.vue"),
        meta: { title: "题目集管理" },
      },
      {
        path: "problemSet/create",
        name: "AdminProblemSetCreate",
        component: () => import("@/views/admin/problemSet/create.vue"),
        meta: { title: "创建题目集", hidden: true },
      },
    ],
  },
];

// 题目相关路由（仅用于直接访问，不显示在侧边栏）
export const problemRoutes = [
  {
    path: "/problem",
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: ":id",
        name: "ProblemDetail",
        component: () => import("@/views/problem/detail.vue"),
        meta: { title: "题目详情", hidden: true },
      },
      {
        path: "solve/:id",
        name: "ProblemSolve",
        component: () => import("@/views/problem/solve.vue"),
        meta: { title: "在线做题", hidden: true },
      },
    ],
  },
];

// 路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...constantRoutes, ...asyncRoutes, ...problemRoutes],
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 };
  },
});

// 检查路由权限
function hasPermission(route, userInfo) {
  if (!route.meta || !route.meta.roles) {
    return true;
  }
  return route.meta.roles.includes(userInfo?.role);
}

// 导航守卫
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  const usersStore = useUsersStore();

  if (usersStore.isLoggedIn) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (!usersStore.userInfo) {
        try {
          await usersStore.getUserInfo();

          // 检查权限
          if (hasPermission(to, usersStore.userInfo)) {
            next();
          } else {
            // 权限不足，跳转到首页
            next({ path: "/dashboard" });
          }
        } catch (error) {
          usersStore.logout();
          next("/login");
        }
      } else {
        // 检查权限
        if (hasPermission(to, usersStore.userInfo)) {
          next();
        } else {
          // 权限不足，跳转到首页
          next({ path: "/dashboard" });
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});

export default router;
